import os
import sys
from argparse import ArgumentParser
from subprocess import getoutput

from loguru import logger
from build import GoBuild


class BuildDeb:
	def __init__(self, arm64=True, amd64=True, mips64=False, git=None, html=None):
		"""
		自动构建deb包
		:param arm64: 构建arm包
		:param amd64: 构建amd包
		:param mips64: 构建mips包
		"""
		self.html = html
		try:
			with open(file="ver.txt", mode='r', encoding="utf8") as r:
				self.version = r.read()
		except Exception as e:
			logger.error(str(e))
			logger.error("版本获取失败")
			sys.exit(2)
		self.build_app = GoBuild(file="ddns.go", name="com.liumou.ddns-tencent",
		                         mips64=mips64, linux=True, arm64=arm64, amd64=amd64)
		self.build_app.pwd = git
		self.build_app.arm32 = True
		self.git = git
		self.work = os.getcwd()
		self.mips64 = mips64
		self.amd64 = amd64
		self.arm64 = arm64
		self.home = os.getenv("HOME")
		self.pack_root = "包所在目录"
		self.debian = ""
		self.postinst = ""
		self.postrm = ""
		self.preinst = ""
		self.control = ""
		self.pack_apps = ""
		self.build_apps_pack = "源码包路径,例如: /root/com.liumou.ddns-tencent/"
		self.files = "源码包files文件夹路径,例如: /root/com.liumou.ddns-tencent/files"
		self.shell_kylin = "麒麟系统专属脚本所在目录"
		self.shell_uos = "uos系统脚本所在目录"
		self.text = ""
		self.html_root = "/home/ml/nginx/html/client/com.liumou.ddns-tencent"
		self.client = ""
		self.build_client = ""
		self.dst = os.path.join(self.html_root, self.client)
		self.client_latest = ""
		self.clt_ver = os.path.join(self.html_root, "version.html")
		self.set_build_arch = "amd64"
		self.set_file_arch = "x86_64"
		self.arch = getoutput("uname -m")
		if self.arch == "aarch64":
			self.arch = "arm64"
		else:
			if self.arch == "mips64" or self.arch == "mips64le":
				self.arch = "mips64le"
			else:
				if str(self.arch).lower() == "x86_64".lower() or str(self.arch) == "amd64" or str(self.arch) == "x86":
					self.arch = "X86_64"
		self.build_arch_list = ["liumou"]
		self.publish_list = []
		self.init()
		self.src = ""
		self.dst = ""

	def _init_ver(self):
		logger.info(f"当前设置版本: {self.version}")
		self.client = f"com.liumou.ddns-tencent_linux-all-{self.version}.deb"
		self.build_client = os.path.join(self.home, f"com.liumou.ddns-tencent_{self.version}.deb")
		self.pack_root = os.path.join(self.home, f"com.liumou.ddns-tencent_{self.version}")
		self.debian = os.path.join(self.pack_root, "DEBIAN")
		self.control = os.path.join(self.pack_root, "DEBIAN/control")
		self.pack_apps = os.path.join(self.pack_root, "opt/apps")
		self.postinst = os.path.join(self.debian, "postinst")
		self.postrm = os.path.join(self.debian, "postrm")
		self.preinst = os.path.join(self.debian, "preinst")
		self.pack_apps = os.path.join(self.pack_root, "opt/apps")
		self.build_apps_pack = os.path.join(self.pack_apps, "com.liumou.ddns-tencent")
		self.files = self.build_apps_pack

	def init(self):
		self._init_ver()

		if not os.path.isdir(self.html_root):
			os.system(f"mkdir -p {os.path.join(self.html_root, 'Release')}")
		if os.path.isdir(self.pack_root):
			os.system(f"rm -rf {self.pack_root}")
		cp = f"cp -rf ./build/com.liumou.ddns-tencent/ {self.pack_root}"
		print(cp)
		os.system(cp)
		if self.arm64:
			self.build_arch_list.append("arm64")
		if self.amd64:
			self.build_arch_list.append("amd64")
		if self.mips64:
			self.build_arch_list.append("mips64le")
		if self.build_app.arm32:
			self.build_arch_list.append('arm')
		# 赋权

		self.build_arch_list.remove("liumou")

	def write_ver(self):
		"""
		写入版本文件
		:return:
		"""
		try:
			with open(file=self.clt_ver, mode="w", encoding="utf8") as w:
				w.write(self.version)
		except Exception as e:
			logger.error(str(e))

	def write(self):
		"""
		写入控制文件信息
		:return:
		"""
		if self.set_build_arch == "X86_64":
			self.set_build_arch = "amd64"
		if self.set_build_arch == "mips64le":
			self.set_build_arch = "mips64el"
		if self.set_build_arch == 'arm':
			self.set_build_arch = "armhf"
		txt = f"""Package: com.liumou.ddns-tencent
Version: {self.version}
Section: utils
Priority: optional
Depends: 
Architecture: {self.set_build_arch}
Homepage: https://liumou.site
Maintainer: 坐公交也用券 <liumou.site@qq.com>
Description: 提供腾讯云DDNS服务\n"""
		try:
			with open(file=self.control, mode='w', encoding="utf8") as w:
				w.write(txt)
		except Exception as e:
			logger.error(str(e))
			sys.exit(3)

	def latest(self):
		"""
		发布最新版
		:return:
		"""
		os.chdir(self.home)
		c = f"cp -rf {self.dst} {self.client_latest}"
		logger.info(f"正在发布最新版: {c}")
		if os.system(c) == 0:
			logger.info("最新版发布成功")
		else:
			logger.warning("最新版发布失败")

	def cp_cmd(self, src, dst, name):
		"""
		Copy Command Exec
		:param name:
		:param src:
		:param dst:
		:return:
		"""
		src = os.path.join(g, "client", f"{src}.bin").replace("X86_64", "amd64")
		logger.info(f"[ {name} ]信息如下")
		logger.info(f"源路径: {src}")
		logger.info(f"目标路径: {dst}")
		c = f"cp -rf {src} {dst}"
		# print(c)
		if os.system(c) == 0:
			logger.info(f"{name}: 复制成功")
		else:
			logger.error(f"{name}: 复制失败")
			sys.exit(2)

	def cp_static(self):
		"""
		复制样式文件
		:return:
		"""
		src = "./static"
		dst = os.path.join(self.files, "static")
		self.cp_cmd(src=src, dst=dst, name="静态文件")

	def cp_ico(self):
		"""
		复制图标文件
		:return:
		"""
		dst = os.path.join(self.files, "favicon.ico")
		src = os.path.join(os.getcwd(), "images/favicon.ico")
		self.cp_cmd(src=src, dst=dst, name="模板文件")

	def cp_client(self):
		"""
		复制客户端文件
		:return:
		"""
		os.chdir(self.work)
		if self.set_build_arch == "amd64":
			self.set_file_arch = "X86_64"
		self.src = f"com.liumou.ddns-tencent_linux-{self.set_file_arch}"
		f = str(os.path.basename(self.src)).replace(".zip", "").replace("amd64", "X86_64")
		self.dst = os.path.join(self.files, str("com.liumou.ddns-tencent_linux"))
		self.cp_cmd(src=self.src, dst=self.dst, name=f"[ {f} ]执行文件")

	def build(self):
		logger.info("文件信息如下")
		print(os.listdir(f"/root/com.liumou.ddns-tencent_{self.version}/opt/apps/com.liumou.ddns-tencent/"))
		os.chdir(self.home)
		logger.debug(f"当前目录：{os.getcwd()}")
		c = f"dpkg-deb -b -Z gzip {os.path.basename(str(self.pack_root))}"
		logger.info(f"执行: {c}")
		if os.system(c) == 0:
			logger.info("构建成功")
		else:
			logger.error("构建失败")
			sys.exit(2)
		if os.system(f"rm -f {self.dst}") != 0:
			print(f"rm -f {self.dst}")
			logger.error("删除失败: ", self.dst)
			sys.exit(2)

	def to_html(self):
		"""
		发布到网站
		:return:
		"""

		self.client = f"com.liumou.ddns-tencent_{self.set_build_arch}-linux_{self.version}.deb"
		self.client_latest = os.path.join(self.html_root, f"com.liumou.ddns-tencent_linux-{self.set_build_arch}_latest.deb")
		self.dst = os.path.join(self.html_root, "Release", self.client)
		src = os.path.join(self.home, f"com.liumou.ddns-tencent_{self.version}.deb")
		if not os.path.isfile(src):
			logger.error(f"源文件不存在: {src}")
			sys.exit(2)
		c = f"cp -rf {src} {self.dst}"
		if os.system(c) == 0:
			logger.info("复制成功")
			self.publish_list.append(f"https://down.liumou.site/client/com.liumou.ddns-tencent/Release/{self.client}")
			self.publish_list.append(f"https://down.liumou.site/client/com.liumou.ddns-tencent/{os.path.basename(self.client_latest)}")
		else:
			logger.error("发布失败")
			print(c)

	def install(self):
		logger.debug(f"当前设置架构: {self.set_build_arch} : 本机架构: {self.arch}")
		if self.set_build_arch == self.arch:
			c = f"dpkg -i {self.build_client}"
			print(c)
			if os.system(c) == 0:
				print("安装成功")
				return True
			return False
		logger.debug("跳过安装")

	def delete(self):
		"""
		删除残留文件
		:return:
		"""
		logger.debug("正在删除残留文件")
		rl = [f"rm -fr {self.pack_root}", f"rm -f {self.build_client}", "rm -f com.liumou.ddns-tencent_*.zip"]
		for i in rl:
			print(i)
			os.system(i)

	def delete_client(self):
		"""
		删除历史客户端文件
		:return:
		"""
		os.system("rm -f com.liumou.ddns-tencent*")

	def chmod(self):
		os.system(f"chmod 0775 {self.preinst}")
		os.system(f"chmod 0775 {self.postrm}")
		os.system(f"chmod 0775 {self.postinst}")

	def start(self):
		"""
		开始
		:return:
		"""
		pwd = os.getcwd()
		self.chmod()
		self.delete_client()
		self.build_app.start()
		self.write_ver()
		for i in self.build_arch_list:
			logger.info(f"构建数量: {len(self.build_arch_list)}")
			print(self.build_arch_list)
			if i == "X86_64":
				i = "amd64"
			self.set_build_arch = i
			self.set_file_arch = i
			self.cp_client()
			self.write()
			self.build()
			self.install()
			self.to_html()
			self.latest()
		self.delete()
		print("发布清单")
		if len(self.publish_list) >= 1:
			for i in self.publish_list:
				print(i)
		c = f"cp -rf {self.html_root} {self.html}"
		print(c)
		os.system(c)
		self.delete_client()
		os.chdir(pwd)


if __name__ == "__main__":
	g = "/root/git/gitee/go/ddns-go"
	c = "/home/ml/nginx/html/client/"
	arg = ArgumentParser(description='自动化打包', prog="布尔传参")
	arg.add_argument('--debug', action='store_true', help='Enable debug mode')
	arg.add_argument('-g', '--git', type=str, help=f"设置项目源码路径,默认: {g}", default=g, required=False)
	arg.add_argument('-c', '--client', type=str, help=f"设置发布路径,默认: {c}", default=c, required=False)
	args = arg.parse_args()
	args_d = args.debug
	args_g = args.git
	args_c = args.client
	os.chdir(args_g)
	os.system("git pull")
	bb = BuildDeb(arm64=True, amd64=True, mips64=True, git=g, html=args_c)
	bb.start()
